package project.base.common.config

import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Configuration
import org.springframework.scheduling.annotation.AsyncConfigurer
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
import java.util.concurrent.Executor
import java.util.concurrent.ThreadPoolExecutor

/**
 * 自定义线程池
 * @author 三味
 * @since 2022/3/3 15:11
 */
@Configuration
open class NativeAsyncTaskExecutePool : AsyncConfigurer {

    @Value("\${task.pool.corePoolSize}")
    private val corePoolSize = 0
    @Value("\${task.pool.maxPoolSize}")
    private val maxPoolSize = 0
    @Value("\${task.pool.keepAliveSeconds}")
    private val keepAliveSeconds = 0
    @Value("\${task.pool.queueCapacity}")
    private val queueCapacity = 0

    val logger: Logger = LoggerFactory.getLogger(this.javaClass)

    override fun getAsyncExecutor(): Executor {
        val executor = ThreadPoolTaskExecutor()
        //核心线程池大小
        executor.corePoolSize = corePoolSize
        //最大线程数
        executor.maxPoolSize = maxPoolSize
        //队列容量
        executor.setQueueCapacity(keepAliveSeconds)
        //活跃时间
        executor.keepAliveSeconds = queueCapacity
        //线程名字前缀
        executor.threadNamePrefix = "MyExecutor-"
        executor.setRejectedExecutionHandler(ThreadPoolExecutor.CallerRunsPolicy())
        executor.initialize()
        return executor
    }

    /**
     * 异步任务中异常处理
     * @return
     */
    override fun getAsyncUncaughtExceptionHandler(): AsyncUncaughtExceptionHandler {
        return AsyncUncaughtExceptionHandler { arg0, arg1, _ ->
            logger.error("==========================" + arg0.message + "=======================", arg0)
            logger.error("exception method:" + arg1.name)
        }
    }
}
